use actix_multipart::Multipart;
use actix_web::{web, Error, Responder, post};
use futures_util::stream::StreamExt as _;
use futures_util::TryStreamExt;
use std::io::Write;
use std::fs::File;
use std::path::PathBuf;

#[post("/upload")]
async fn upload(mut payload: Multipart) -> Result<impl Responder, Error> {
    while let Some(item) = payload.try_next().await? {
        let mut field = item;
        let content_disposition = field.content_disposition();

        if let Some(filename) = content_disposition.get_filename() {
            let filepath = PathBuf::from("./uploads").join(filename);
            let mut f = web::block(|| File::create(filepath)).await??;

            while let Some(chunk) = field.next().await {
                let data = chunk?;
                f = web::block(move || f.write_all(&data).map(|_| f)).await??;
            }
        }
    }
    Ok(web::Json("File uploaded successfully"))
}